package com.misboot.document.controller;

import cn.ewsd.common.annotation.ControllerLog;
import cn.ewsd.common.utils.StringUtils;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.misboot.document.model.DfsFile;
import com.misboot.document.service.DfsFileService;
import com.misboot.document.utils.BaseUtils;
import com.misboot.document.utils.PageUtil.PageParam;
import com.misboot.document.utils.PageUtil.PageSet;
import com.misboot.document.utils.Result;
import com.misboot.document.utils.minio.MinioUtil;
import io.swagger.annotations.*;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;
import com.alibaba.fastjson.JSON;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分布式文件管理
 *
 * @Author 湖南佐佑时代科技有限公司
 * @Email service@zuoyo.com
 * @Date 2019-02-19 14:20:45
 */
@Api(tags = {"分布式文件管理模块"})
@Controller
@RequestMapping("/fastdfs")
public class DfsFileController extends DocumentBaseController {

    @Autowired
    private DfsFileService dfsFileService;

    @Autowired
    MinioUtil minioUtil;
    //地址
    @Value("${minio.url}")
    private String minioUrl;

    @Autowired
    private MinioController minioController;


    @ResponseBody
    @RequestMapping(value = "/getPageSet", method = RequestMethod.POST)
    @ControllerLog(description = "获得DfsFile分页集数据")
    @ApiOperation(value = "获得分布式文件分页集数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", defaultValue = "1", required = true, dataType = "Int"),
            @ApiImplicitParam(name = "rows", value = "一页显示多少条记录", defaultValue = "20", required = true, dataType = "Int"),
            @ApiImplicitParam(name = "sort", value = "排序", defaultValue = "createTime", required = true, dataType = "String"),
            @ApiImplicitParam(name = "order", value = "排序规则", defaultValue = "desc", required = true, dataType = "String")
    })
    public Object getPageSet(PageParam pageParam, String fileName, String puuid) {
        String filterSort = "";
        filterSort = BaseUtils.filterSort(request, filterSort);
        PageSet<DfsFile> pageSet = dfsFileService.getPageSet(pageParam, filterSort, fileName, puuid);
        return pageSet;
    }

    @ResponseBody
    @RequestMapping(value = "/getDataCountByPuuid", method = RequestMethod.POST)
    public Result getDataCountByPuuid(String puuid) {
        String count = dfsFileService.getDataCountByPuuid(puuid);
        return Result.ofSuccess(count);
    }

    @ResponseBody
    @RequestMapping(value = "/getOaPageSet", method = RequestMethod.POST)
    @ControllerLog(description = "获得DfsFile分页集数据")
    @ApiOperation(value = "获得分布式文件分页集数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", defaultValue = "1", required = true, dataType = "Int"),
            @ApiImplicitParam(name = "rows", value = "一页显示多少条记录", defaultValue = "20", required = true, dataType = "Int"),
            @ApiImplicitParam(name = "sort", value = "排序", defaultValue = "createTime", required = true, dataType = "String"),
            @ApiImplicitParam(name = "order", value = "排序规则", defaultValue = "desc", required = true, dataType = "String")
    })
    public Object getOaPageSet(PageParam pageParam, String puuid) {
        String filterSort = "";
        PageSet<DfsFile> pageSet = new PageSet<DfsFile>();
        if (StringUtils.isNullOrEmpty(puuid)) {
            return pageSet;
        }
        List<String> list = dfsFileService.getAccessorylByOaRelevanceUuid(puuid);
        if (list == null || list.size() == 0) {
            return pageSet;
        }
        filterSort = BaseUtils.filterSort(request, filterSort);
        pageSet = dfsFileService.getOaPageSet(pageParam, filterSort, list);
        return pageSet;
    }

    @ResponseBody
    @RequestMapping(value = "/getListByPuuid", method = RequestMethod.POST)
    public Object getListByPuuid(String puuid) {
        String filterSort = "";
        List <DfsFile> dfsFileList = new ArrayList<DfsFile>();
        if (StringUtils.isNullOrEmpty(puuid)) {
            return dfsFileList;
        }
        else
        {
            filterSort += " and puuid = '"+ puuid +"' ";
        }
        filterSort = BaseUtils.filterSort(request, filterSort);
        return dfsFileService.getListByPuuid(filterSort);
    }

    @ResponseBody
    @RequestMapping(value = "/getFileByUrl", method = RequestMethod.POST)
    public Object getFileByUrl(String url) {
        String filterSort = "";
        List <DfsFile> dfsFileList = new ArrayList<DfsFile>();
        if (StringUtils.isNullOrEmpty(url)) {
            return dfsFileList;
        }
        else
        {
            filterSort += " and url = '"+ url +"' ";
        }
        filterSort = BaseUtils.filterSort(request, filterSort);
        return dfsFileService.getListByPuuid(filterSort);
    }

    @ResponseBody
    @RequestMapping(value = "/getPageSetUuids", method = RequestMethod.POST)
    @ControllerLog(description = "获得DfsFile分页集数据")
    @ApiOperation(value = "获得分布式文件分页集数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", defaultValue = "1", required = true, dataType = "Int"),
            @ApiImplicitParam(name = "rows", value = "一页显示多少条记录", defaultValue = "20", required = true, dataType = "Int"),
            @ApiImplicitParam(name = "sort", value = "排序", defaultValue = "createTime", required = true, dataType = "String"),
            @ApiImplicitParam(name = "order", value = "排序规则", defaultValue = "desc", required = true, dataType = "String")
    })
    public Object getPageSetUuids(PageParam pageParam, String uuids) {
        String filterSort = "";
//        String[] uuidArr;
        PageSet<DfsFile> pageSet = new PageSet<DfsFile>();
        if (StringUtils.isNullOrEmpty(uuids)) {
//            uuidArr = uuids.split(",");
//            filterSort += " and uuid in("+ uuids + ") ";
            return pageSet;
        }
        filterSort = BaseUtils.filterSort(request, filterSort);
        pageSet = dfsFileService.getPageSetUuids(pageParam, filterSort, uuids);
        return pageSet;
    }


    @ResponseBody
    @RequestMapping(value = "/getDetailByUuid", method = RequestMethod.GET)
    @ControllerLog(description = "获得DfsFile模块详细数据")
    @ApiOperation(value = "获得分布式文件模块详细数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "uuid", value = "标识", required = true, dataType = "String")
    })
    public Object getDetailByUuid(String uuid) {
        DfsFile dfsFile = dfsFileService.selectByPrimaryKey(uuid);
        return dfsFile;
    }


    @ResponseBody
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ControllerLog(description = "保存DfsFile模块数据")
    public Object save(@ModelAttribute DfsFile dfsFile) {
        int result = dfsFileService.insertSelective(getSaveData(dfsFile));
        return result > 0 ? success("保存成功！") : failure("保存失败！");
    }

    @ResponseBody
    @RequestMapping(value = "/saveData", method = RequestMethod.POST)
    public void saveData(@RequestBody String filestr) {
        List<Map<String, Object>> files = JSON.parseObject(filestr, List.class);
        for (Map<String, Object> file : files) {
            // 先判断是否存在
            DfsFile e =  dfsFileService.selectByPrimaryKey(MapUtils.getString(file, "uuid", ""));
            if (null != e) {
                continue;
            }
            DfsFile dfsFile = new DfsFile();
            dfsFile.setCreator(MapUtils.getString(file, "creator", ""));
            dfsFile.setFileName(MapUtils.getString(file, "fileName", ""));
            dfsFile.setCreatorId(MapUtils.getString(file, "creatorId", ""));
            dfsFile.setRemark(MapUtils.getString(file, "remark", ""));
            dfsFile.setUuid(MapUtils.getString(file, "uuid", ""));
            dfsFile.setVersion(MapUtils.getString(file, "version", ""));
            dfsFile.setUrl(MapUtils.getString(file, "url", ""));
            dfsFile.setFileSize(MapUtils.getString(file, "fileSize", ""));
            dfsFile.setCreatorOrgId(MapUtils.getInteger(file, "creatorOrgId", 0));
            dfsFile.setTenantUuid(MapUtils.getString(file, "tenantUuid", ""));
            dfsFileService.insertSelective(getSaveData(dfsFile));
        }
    }


    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    @ControllerLog(description = "更新DfsFile模块数据")
    public Object update(@ModelAttribute DfsFile dfsFile) {
        int result = dfsFileService.updateByPrimaryKeySelective(getUpdateData(dfsFile));
        return result > 0 ? success("更新成功！") : failure("更新失败！");
    }


    @ResponseBody
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.POST)
    @ControllerLog(description = "删除DfsFile模块数据")
    public Object deleteBatch(@RequestParam String[] uuid) {
        int result = dfsFileService.executeDeleteBatch(uuid);
        return result > 0 ? success("删除成功！") : failure("删除失败！");
    }

    @ResponseBody
    @RequestMapping(value = "/deleteDfsFile", method = RequestMethod.POST)
    @ControllerLog(description = "删除DfsFile模块数据")
    public Object deleteDfsFile(@RequestParam String[] uuid,String url) {
        int  result = dfsFileService.executeDeleteBatch(uuid);
        String objectNames = "";
        String bucket = "";
        if (result>0){
            if (uuid != null && uuid.length > 0){
                for (String id : uuid){
                    String name = url.replace(minioUrl,"");
                    bucket = name.substring(0,name.indexOf("/"));
                    objectNames += name.substring(name.indexOf("/"))+",";
                }
                objectNames = objectNames.substring(0,objectNames.length()-1);
            }
            try {
                minioController.deleteFile(bucket,objectNames);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result > 0 ? success("删除成功！") : failure("删除失败！");
    }

    @ResponseBody
    @RequestMapping(value = "/deleteDfsFiles", method = RequestMethod.POST)
    @ControllerLog(description = "删除DfsFile模块数据")
    public Object deleteDfsFiles(String uuidArray) {
        int  result = 0;
        if (!StringUtils.isNullOrEmpty(uuidArray)){
            String[] uuids = uuidArray.split(",");
            List<DfsFile> dfsFiles = dfsFileService.getDfsFileByPuuids(uuids);
            String objectNames = "";
            String bucket = "";
            if (dfsFiles != null && dfsFiles.size() > 0){
                for (DfsFile dfsFile : dfsFiles){
                    String name = dfsFile.getUrl().replace(minioUrl,"");
                    bucket = name.substring(0,name.indexOf("/"));
                    objectNames += name.substring(name.indexOf("/"))+",";
                }
                objectNames = objectNames.substring(0,objectNames.length()-1);
            }
            try {
                minioController.deleteFile(bucket,objectNames);
                result = dfsFileService.deleteDfsFiles(uuids);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return result > 0 ? success("删除成功！") : failure("删除失败！");
    }

    @ResponseBody
    @RequestMapping(value = "/delFile", method = RequestMethod.POST)
    @ControllerLog(description = "删除文件")
    @ApiOperation(value = "删除文件方法")
    public Object delFile(@RequestBody List<String> uuids) {

        for (String uuid:uuids) {
            String name = dfsFileService.getFileNameByUuid(uuid);
            dfsFileService.executeDeleteByName(name);
            try {
                minioUtil.deleteObject("vue-accessory", name);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return success("删除成功！");
    }


    @RequestMapping(value = "/getBucketByUrl", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> getBucketByUrl(String fileuUrl) throws Exception {
        if (StringUtils.isNullOrEmpty(fileuUrl)){
            return null;
        }
        Map<String,Object> map = new HashMap<String,Object>();
        fileuUrl = fileuUrl.replace(minioUrl, "");
        String bucket = fileuUrl.substring(0, fileuUrl.indexOf("/"));
        String objectName = fileuUrl.substring(fileuUrl.indexOf("/")+1);
        map.put("bucket",bucket);
        map.put("objectName",objectName);
        return map;
    }

    @ResponseBody
    @RequestMapping(value = "/getListByUuids", method = RequestMethod.POST)
    @ApiOperation(value = "获得分布式文件模块详细数据")
    public Object getListByUuids(@RequestBody String inParams) {
        JSONObject jsonObject = JSONObject.parseObject(inParams);
        JSONArray uuids = jsonObject.getJSONArray("uuids");
        Example example = new Example(DfsFile.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("uuid", uuids);
        return dfsFileService.selectByExample(example);
    }

}
